package com.example.tms.util;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import com.example.tms.entity.Employee;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

@Component
public class JwtTokenUtil {
    private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtil.class);

    // 256-bit Base64 encoded key
    private static final String SECRET_KEY = "U2FsdGVkX1+pqALkZ8L7vVlz5JkKb5n7x9y0B2Qa4rE=";
    private static final long EXPIRATION_TIME = 86400000; // 24小时

    public String generateToken(Employee employee) {
        if (employee.getId() == null) {
            throw new IllegalArgumentException("Employee ID cannot be null");
        }
        Map<String, Object> claims = new HashMap<>();
        
        // 标准化角色名称
        String role = switch(employee.getEmpType()) {
            case "系统管理员" -> "ADMIN";
            case "高层" -> "EXECUTIVE";
            case "人事专员" -> "HR";
            default -> "USER";
        };
        
        claims.put("empType", employee.getEmpType());
        claims.put("role", role); // 添加标准化的角色声明
        claims.put("phone", employee.getPhone());
        
        return createToken(claims, String.valueOf(employee.getId()));
    }

    public String generateToken(UserDetails userDetails) {
        if (userDetails instanceof Employee) {
            return generateToken((Employee) userDetails);
        }
        throw new IllegalArgumentException("Unsupported UserDetails type");
    }

    private String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(getSignInKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    private Claims extractAllClaims(String token) {
        return Jwts.parser()
                .setSigningKey(getSignInKey())
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

    private Key getSignInKey() {
        byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY);
        return Keys.hmacShaKeyFor(keyBytes);
    }

    public boolean validateToken(String token, UserDetails userDetails) {
        final String tokenUsername = extractUsername(token);
        final String userDetailsUsername = userDetails.getUsername();
        
        if (!tokenUsername.equals(userDetailsUsername)) {
            return false;
        }
        
        return !isTokenExpired(token);
    }

    private boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }
}
